/*
 * @Author: yt 2399493770@qq.com
 * @Date: 2024-04-25 22:23:11
 * @LastEditors: yt 2399493770@qq.com
 * @LastEditTime: 2024-04-26 00:22:13
 * @Description:
 */
import { ObjectSchema } from "joi";
import { Request, Response } from "express";
import { handlerType } from "../types";
import { jwtMiddleware } from "./jwtMiddleware";
import { validateMiddleware } from "./validateMiddleware";
import { errorHandler } from "./errorHandler";
import { BasicsResult } from "./BasicsResult";

export { apiHandler };

function isPublicPath(req: Request) {
  // public routes that don't require authentication
  const publicPaths = [
    "POST:/api/auth/login",
    "POST:/api/auth/logout",
    "POST:/api/auth/register",
  ];
  return publicPaths.includes(`${req.method}:${req.path}`);
}

type handlerOptions = {
  schema: ObjectSchema;
  isJwt: boolean;
};

function apiHandler(
  handler: handlerType,
  { schema, isJwt = false }: handlerOptions
) {
  return async function (req: Request, res: Response, args: any = {}) {
    try {
      if (!isPublicPath(req)) {
        await jwtMiddleware(req, isJwt);
        await validateMiddleware(args, schema);
      }
      // route handler
      const responseBody = await handler(req, args);
      res.json(BasicsResult.success(responseBody));
    } catch (err) {
      console.log("global error handler", err);
      // 通用错误
      const errData = errorHandler(err);
      res.status(errData.code).json(errData);
    }
  };
}

// const updateRole = apiHandler(
//   async (req, { params }) => {
//     // const { id } = params;
//     // const {body} = req.body
//     // await usersRepo.update(id, body);
//     // return setJson({
//     //   message: "更新成功",
//     // });
//   },
//   {
//     isJwt: true,
//     schema: joi.object({
//       role: joi.string().required().valid("user", "admin"),
//     }),
//   }
// );
